import config from "./config.js";
function logout() {
  uni.showToast({
    title: "登录失效",
    icon: "none",
  });
  uni.removeStorageSync("token");
  uni.removeStorageSync("userInfo");
  uni.reLaunch({ url: "/pages/login" });
}
export default {
  request(options = {}) {
    return new Promise((resolve, reject) => {
      const token = uni.getStorageSync("token");

      options.url = config.baseUrl + options.url;
      options.header.authorization = token;
      options.complete = (response) => {
        if (response.statusCode === 200) {
          if (response.code === 401 || response.data?.code === 401) {
            logout();
          }
          resolve(response.data);
        } else {
          if (response.code === 401 || response.data?.code === 401) {
            logout();
          }
        }
      };

      uni.request(options);
    });
  },

  post(url, data = {}, header = {}) {
    let options = {
      url: url,
      data: data,
      header,
      // header: { ...header, 'Content-Type': 'application/x-www-form-urlencoded' },
      method: "POST",
    };

    return this.request(options);
  },

  get(url, data = {}, header = {}) {
    let options = {
      url: url,
      data: data,
      header: header,
    };

    return this.request(options);
  },
};
